import re
from lly.android.network import get_phone_ip
from lly.vim.command import execute_os_cmd, KEY_RETURNCODE, cmd_result_path, KEY_STD_OUT


def connect_by_ip(port=5555):
    '''
    通过ip连接手机adb
    '''
    ips = get_phone_ip()
    host = ips[0]
    for device in get_connect_devices():
        if device[0].startswith(host):
            return
    cmds = [f'adb tcpip {port}',
            f'adb connect {host}:{port}']
    cmd_result = execute_os_cmd('&'.join(cmds))
    if cmd_result[KEY_RETURNCODE] != 0:
        raise Exception(cmd_result)


def get_connect_devices():
    '''
    通过adb devices -l 获取已连接设备
    ，然后过滤相应的ip信息
    格式如
        192.168.1.102:5555     device product:tiffany model:MI_5X device:tiffany transport_id:48
    '''
    cmd = 'adb devices -l'
    cmd_result = execute_os_cmd(cmd)
    if cmd_result[KEY_RETURNCODE] != 0:
        raise Exception[cmd_result]
    device_regx = r"(?P<ip>[\d.]+:\d+).*?model:(?P<model>\w+)"
    current_connects = []
    with cmd_result_path(cmd_result[KEY_STD_OUT]).open('r', encoding='utf-8') as f:
        for match in re.finditer(device_regx, f.read()):
            current_connects.append((match['ip'], match['model']))
    return current_connects


def disconnect_by_ip(ip):
    '''
    关闭通过ip连接的设备
    '''
    cmd = f'adb disconnect {ip}'
    cmd_result = execute_os_cmd(cmd)
    if cmd_result[KEY_RETURNCODE] != 0:
        raise Exception(cmd_result)


def test_connect_by_ip():
    '''test connect'''
    connect_by_ip()
    assert len(get_connect_devices()) > 0
